package com.zhengqiangblog.blog.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.PropertyConfigurator;

public class Log4jConfigListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String basePath = getBasePath();
        String localHostName = getLocalHostName();
        Properties properties = new Properties();
        String propertiesPath = basePath + localHostName + ".log4j.properties";
        servletContext.log("Initializing log4j from [" + propertiesPath + "]");
        File propertiesFile = new File(propertiesPath);
        try (InputStream in = new BufferedInputStream(new FileInputStream(propertiesFile))) {
            properties.load(in);
        } catch (Exception e) {
            servletContext.log(e.getMessage(), e);
        }
        PropertyConfigurator.configure(properties);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    private static String getLocalHostName() {
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
        }
        if (localHost != null) {
            return localHost.getHostName();
        }
        return null;
    }

    private static String getBasePath() {
        return Log4jConfigListener.class.getResource("/").getPath();
    }

}
